package com.framework.test.utils;

import io.restassured.config.SSLConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.framework.test.utils.ConfigurationManager;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

/**
 * SSL配置工具类
 * 提供SSL证书验证的各种配置选项
 */
public class SSLUtil {
    
    private static final Logger logger = LogManager.getLogger(SSLUtil.class);
    
    /**
     * 获取SSL配置
     * 根据配置文件中的设置返回相应的SSL配置
     * 
     * @return SSLConfig对象
     */
    public static SSLConfig getSSLConfig() {
        boolean relaxedValidation = Boolean.parseBoolean(
            ConfigurationManager.getProperty("ssl.relaxedValidation", "false")
        );

        if (relaxedValidation) {
            logger.info("启用SSL宽松验证模式 - 忽略证书验证");
            return createRelaxedSSLConfig();
        }

        // 检查是否配置了自定义信任库
        String trustStorePath = ConfigurationManager.getProperty("ssl.truststore.path", "");
        if (!trustStorePath.isEmpty()) {
            String trustStorePassword = ConfigurationManager.getProperty("ssl.truststore.password", "");
            logger.info("使用自定义信任库: " + trustStorePath);
            return createCustomTrustStoreConfig(trustStorePath, trustStorePassword);
        }

        // 默认SSL配置
        logger.info("使用默认SSL配置");
        return new SSLConfig();

    }
    
    /**
     * 创建宽松的SSL配置
     * 忽略所有SSL证书验证
     * 
     * @return 宽松的SSLConfig
     */
    private static SSLConfig createRelaxedSSLConfig() {
        return new SSLConfig()
            .relaxedHTTPSValidation()
            .allowAllHostnames();
    }
    
    /**
     * 创建自定义信任库的SSL配置
     * 
     * @param trustStorePath 信任库路径
     * @param trustStorePassword 信任库密码
     * @return 自定义信任库的SSLConfig
     */
    private static SSLConfig createCustomTrustStoreConfig(String trustStorePath, String trustStorePassword) {
        try {
            KeyStore trustStore = KeyStore.getInstance("JKS");
            try (FileInputStream fis = new FileInputStream(trustStorePath)) {
                trustStore.load(fis, trustStorePassword.toCharArray());
            }
            
            return new SSLConfig()
                .trustStore(trustStore)
                .and()
                .allowAllHostnames();
                
        } catch (Exception e) {
            logger.error("加载自定义信任库失败: " + e.getMessage());
            logger.info("回退到宽松SSL验证模式");
            return createRelaxedSSLConfig();
        }
    }
    
    /**
     * 创建完全信任所有证书的TrustManager
     * 仅用于测试环境，生产环境不建议使用
     * 
     * @return TrustManager数组
     */
    public static TrustManager[] createTrustAllManager() {
        return new TrustManager[] {
            new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    // 信任所有客户端证书
                }
                
                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    // 信任所有服务器证书
                }
            }
        };
    }
    
    /**
     * 设置全局SSL上下文以忽略证书验证
     * 这会影响整个JVM的SSL行为，请谨慎使用
     */
    public static void setGlobalSSLContext() {
        try {
            boolean relaxedValidation = Boolean.parseBoolean(
                ConfigurationManager.getProperty("ssl.relaxedValidation", "false")
            );
            
            if (relaxedValidation) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, createTrustAllManager(), new java.security.SecureRandom());
                
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true; // 信任所有主机名
                    }
                });
                
                logger.info("已设置全局SSL上下文为宽松验证模式");
            }
        } catch (Exception e) {
            logger.error("设置全局SSL上下文失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证SSL配置是否正确
     * 
     * @param url 测试URL
     * @return 验证结果
     */
    public static boolean validateSSLConfig(String url) {
        try {
            // 这里可以添加SSL配置验证逻辑
            logger.info("SSL配置验证通过: " + url);
            return true;
        } catch (Exception e) {
            logger.error("SSL配置验证失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取SSL配置信息
     * 
     * @return SSL配置信息字符串
     */
    public static String getSSLConfigInfo() {
        StringBuilder info = new StringBuilder();
        info.append("SSL配置信息:\n");

        boolean relaxedValidation = Boolean.parseBoolean(
            ConfigurationManager.getProperty("ssl.relaxedValidation", "false")
        );
        info.append("- 宽松验证模式: ").append(relaxedValidation ? "启用" : "禁用").append("\n");

        String trustStorePath = ConfigurationManager.getProperty("ssl.truststore.path", "");
        if (!trustStorePath.isEmpty()) {
            info.append("- 自定义信任库: ").append(trustStorePath).append("\n");
        } else {
            info.append("- 信任库: 使用系统默认\n");
        }

        return info.toString();
    }
}